package com.indusfo.spc.controller;

import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.IPalletsService;
import com.indusfo.spc.untlis.GsonUtil;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;


/**
 *
 * @author chenm
 * @date 2019/07/08 15:50
 *
 */
@Controller
@RequestMapping("/pallets")
public class PalletsController {

	@Resource
	private IPalletsService palletService;

	/**
	 * 新增
	 *
	 * @author chenm
	 * @date 2019/07/09 13:32
	 * @param [pallets]
	 * @return com.indusfo.spc.vo.JSONObject
	 */
	@RequestMapping(value = "/insertPallets", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject insertPallets(Pallets pallets) {
		JSONObject json = palletService.insertPallets(pallets);
		return json;
	}


	/**
	 * 删除
	 *
	 * @author chenm
	 * @date 2019/07/09 13:34
	 * @param [palIds,
	 *            lDataState]
	 * @return com.indusfo.spc.vo.JSONObject
	 */
	@RequestMapping(value = "/deletePallets", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject deletePallets(Integer[] palIds, Integer dataState) {
		dataState = 2;
		JSONObject json = palletService.deletePallets(palIds, dataState);
		return json;
	}

	/**
	 * 更新
	 *
	 * @author chenm
	 * @date 2019/07/09 13:38
	 * @param [pallets]
	 * @return com.indusfo.spc.vo.JSONObject
	 */
	@RequestMapping(value = "/updatePallets", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject updatePallets(Pallets pallets) {

		JSONObject json = palletService.updatePallets(pallets);
		return json;

	}

	/**
	 * 启用/停用
	 *
	 * @author chenm
	 * @date 2019/07/09 13:42
	 * @param [lPalIds,
	 *            lDataState]
	 * @return com.indusfo.spc.vo.JSONObject
	 */
	@RequestMapping(value = "/definesPallets", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject definesPallets(Integer[] palIds, Integer dataState) {
		JSONObject json = palletService.deletePallets(palIds, dataState);
		return json;
	}

	/**
	 * 查询
	 *
	 * @author chenm
	 * @date 2019/07/09 13:50
	 * @param [pallets]
	 * @return com.indusfo.spc.vo.JSONObject
	 */
	@RequestMapping(value = "/queryPallets")
	@ResponseBody
	public JSONObject queryPallets(Pallets pallets) {

		JSONObject json = palletService.queryPallets(pallets);
		return json;

	}
	@RequestMapping("/uploadFilePallets")
	@ResponseBody
	public JSONObject uploadFileUser(@RequestParam("file") MultipartFile file, Boolean way, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {
		//定义一个message对象用于向前台传输数据
		Message msg = new Message();
		//设置错误集合的
		List<ExcelErrorData> errorDatas = new ArrayList<>();
		response.setContentType("text/html;charset=UTF-8");
		//判断上传文件格式是否正确
		Workbook wb = ExcelUtil.getWorkbook(file.getInputStream(), ExcelUtil.isExcel2007(file.getOriginalFilename()));
		if (wb == null) {
			errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "文件解析错误"));
		} else {
			//获取excel文件的第一个sheet
			Sheet sheet = wb.getSheetAt(0);
			if (sheet == null) {
				msg.setCode(2);
				msg.setMsg("未找到需要导入的表格");
				errorDatas.add(ExcelErrorData.getExcelErrorData(0, 0, "未找到需要导入的表格"));
			} else {
				//获取最后一行的行号
				int rowCount = sheet.getLastRowNum();
				if (rowCount < 1) {
					msg.setCode(1);
					msg.setMsg("未找到需要导入的数据，请确认表格是否保存！！！");
					errorDatas.add(ExcelErrorData.getExcelErrorData(0, "未找到需要导入的数据，请确认表格是否保存！！！"));
				} else {
					List<Pallets> addProductPlans = new ArrayList<>();
					for (int i = 1; i <= rowCount; i++) {
						boolean needAdd = true;
						//获取到每一行的每一列的数据
						//托盘编号
						String palCode =com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 0, false);
						//托盘名称
						String palName = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 1, false);
						//生产任务单
						String moderno = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 2, false);
						//批号
						String batchno = com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, i, 3, false);

						Pallets plan = new Pallets(palCode,palName,moderno,batchno);
						int m = i + 1;
						//将excel中的每一行数据存储进行检查
						String result = palletService.checkNoRepeatExcel(plan);
						if(result!=null){
							errorDatas.add(ExcelErrorData.getExcelErrorData(i, result));
							needAdd=false;
						}
						for (int j = 1; j < i; j++) {
							//判断检测项目编码
							String oldpalCode = StringUtils.trimToEmpty(com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 0, false)).replaceAll("\\s*", "");
							String oldpalName = StringUtils.trimToEmpty(com.indusfo.spc.untlis.ExcelUtil.getCellValue(sheet, j, 1, false)).replaceAll("\\s*", "");
							if (StringUtils.isBlank(palCode) && oldpalCode.equals(palCode)) {
								needAdd = false;
								errorDatas.add( ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同检测托盘编码"));
							}
							if (StringUtils.isBlank(palName) && oldpalName.equals(palName)) {
								needAdd = false;
								errorDatas.add( ExcelErrorData.getExcelErrorData(i, "与表格中第" + j + "行存在相同检测托盘名称"));
							}
						}
						if (needAdd) {
							addProductPlans.add(plan);
						} else {
							msg.setCode(2);
							msg.setMsg("导入数据中存在异常信息");
						}

					}
					//根据这些来判断是否是中止导入还是跳过继续进行导入
					if (msg.getCode() == 2 && !way) {
						msg.setMsg(msg.getMsg() + ",中止导入");
					} else {
						if (addProductPlans.size() > 0) {
							try {
								palletService.updateListPallet(addProductPlans);
								//当程序执行到这里时,判断信息是否为空为空的话设置导入成功
								msg.setMsg(StringUtils.isBlank(msg.getMsg()) ? "导入成功" : msg.getMsg());
								if ("导入成功".equals(msg.getMsg())) {
									msg.setCode(1);
								}
							} catch (Exception e) {
								e.printStackTrace();
								msg.setMsg("导入失败");
							}
						}
					}
					//msg.setData(GsonUtil.toJson(errorDatas));
				}
			}
		}
		msg.setData(GsonUtil.toJson(errorDatas));
		//response.getWriter().println(GsonUtil.toJson(msg));
		String s = GsonUtil.toJson(msg);
		return JSONObject.build(200,msg.getMsg(),errorDatas);
	}

}
